<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="选择店铺：" prop="storeId">
        <el-select v-model="queryParams.storeId" placeholder="请选择店铺" filterable>
          <el-option v-for="(item,index) in storeList" :key="index"
                     :label="item.storeUserName + ' - ' + item.storeName "
                     :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="店铺类型" prop="storeType">
        <el-select v-model="queryParams.storeType" placeholder="请选择店铺类型" clearable size="small">
          <el-option
            v-for="dict in dict.type.erp_seller_store_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="别名" prop="storeAlias">
        <el-input size="small" v-model="queryParams.storeAlias" placeholder="请输入别名"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeInfoList" @selection-change="handleSelectionChange" border stripe>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="店铺名称" align="center" prop="storeName"/>
      <el-table-column label="店铺类型" align="center" prop="code">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.erp_seller_store_type" :value="scope.row.storeType"/>
        </template>
      </el-table-column>
      <el-table-column label="别名" align="center" prop="storeAlias"/>
      <el-table-column label="订单数量" align="center" prop="orderCount"/>
      <el-table-column label="订单金额（元）" align="center" prop="orderAmount"/>
      <el-table-column label="利润（元）" align="center" prop="profit"/>
      <el-table-column label="利润率（%）" align="center" prop="profitRatio"/>
      <el-table-column label="广告投入（元）" align="center" prop="adInvestment"/>
      <el-table-column label="状态" align="center" prop="adInvestment">
        <template slot-scope="scope">
          <div>{{ scope.row.isBind == '1' ? '已绑定' : '未绑定' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.isBind =='1' " size="mini" type="text" @click="handleEdit(scope.row)">修改
          </el-button>
          <el-button v-if="scope.row.isBind =='0' " size="mini" type="text" @click="openBingErpModal(scope.row)">
            绑定ERP
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--  店铺绑定erp弹窗  -->
    <el-dialog
      title="绑定erp"
      :visible.sync="isOpenBingErpModal"
      width="500px"
      :before-close="closeModal">
      <el-form size="small" :model="form" :rules="rules" ref="formRef"
               label-width="120px">
        <el-form-item label="店铺账号" prop="storeUserName">
          <el-input size="small" disabled v-model="form.storeUserName" placeholder="请输入店铺账号"/>
        </el-form-item>
        <el-form-item label="分公司名称：" prop="branchId">
          <el-select v-model="form.branchId" filterable clearable placeholder="请选择所属分公司" @change="getAgentList">
            <el-option v-for="item in companyList" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="代理名称：" prop="agentId">
          <el-select v-model="form.agentId" filterable
                     placeholder="请选择所属代理" @change="getPersonalList" clearable>
            <el-option v-for="item in pushAgentList" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="个人开户名称：" prop="personId">
          <el-select v-model="form.personId" filterable placeholder="请选择直推个人" clearable>
            <el-option v-for="item in parentList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="别名" prop="storeAlias">
          <el-input size="small" v-model="form.storeAlias" placeholder="请输入别名"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeModal">取 消</el-button>
        <el-button type="primary" @click="confirmBing()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import {getAssociationByStore, statisticalData, storeBindErp} from "@/api/shop/shopData";
import {queryAgentByBranchId, queryCompanyList} from "@/api/organize/agent";
import {queryUserInfoByAgentIdagentId} from "@/api/organize/personal";
import {getStoreInfo} from "@/api/order/orderApi";

export default {
  name: "UserInfo",
  dicts: ['erp_seller_store_type'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 个人开户信息表格数据
      storeInfoList: [],
      // 弹出层标题
      title: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeUserName: undefined,
        storeType: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        branchId: [{required: false, message: "请选择分公司名称", trigger: "change"}],
        agentId: [{required: false, message: "请选择代理名称", trigger: "change"}],
        personId: [{required: false, message: "请选择个人开户名称", trigger: "change"}],
        storeAlias: [{required: false, message: "别名不能为空", trigger: "blur"}],
      },
      isOpenBingErpModal: false,//是否打开店铺绑定erp弹窗
      companyList: [],//分公司列表
      pushAgentList: [],//代理列表
      parentList: [],//个人列表
      storeUserName: '',
      storeId: '',
      storeList: JSON.parse(this.$store.getters.shopList),//店铺列表
    };
  },
  created() {
    this.getCompanyList()
    this.getList();
  },
  methods: {
    // 确定绑定erp
    closeModal() {
      this.isOpenBingErpModal = false
    },
    // 查询分公司和总公司列表
    getCompanyList() {
      this.loading = true;
      queryCompanyList(this.queryParams).then(response => {
          this.companyList = response;
          this.companyList[response.length - 1].value = Number(this.companyList[response.length - 1].value)
          // this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 通过分公司查询代理列表
    getAgentList(e, status) {
      console.log('eee', e)
      let data = {
        branchId: e
      }
      queryAgentByBranchId(data).then(res => {
        this.pushAgentList = res
        if (!status) {
          this.form.agentId = ''
          this.form.personId = ''
        }
      })
    },
    // 通过代理查询个人用户列表
    getPersonalList(e, status) {
      let data = {
        agentId: e
      }
      queryUserInfoByAgentIdagentId(data).then(res => {
        this.parentList = res
        if (!status) {
          this.form.personId = ''
        }
      })
    },
    // 打开绑定erp弹窗
    openBingErpModal(row) {
      this.storeUserName = row.storeUserName
      this.storeId = row.storeId
      // this.handleEdit(row)
      this.reset();
      this.isOpenBingErpModal = true
    },
    // 修改店铺绑定erp
    handleEdit(row) {
      this.title = '修改已绑定erp的店铺信息'
      let data = {
        storeId: row.storeId,
        storeUserName: row.storeUserName
      }
      getAssociationByStore(data).then(res => {
        this.form = res.data
        this.getAgentList(res.data.branchId, '1')
        this.getPersonalList(res.data.agentId, '1')
        console.log('this.form', this.form)
        this.isOpenBingErpModal = true
      })
    },
    // 店铺绑定erp
    confirmBing(row) {
      this.$refs["formRef"].validate(valid => {
        if (valid) {
          this.form.storeId = this.storeId
          storeBindErp(this.form).then(res => {
            this.$message.success(res.msg)
            this.isOpenBingErpModal = false;
            this.getList()
          })
        }
      });
    },
    /** 查询个人开户信息列表 */
    getList() {
      this.loading = true;
      statisticalData(this.queryParams).then(response => {
        this.storeInfoList = response.rows;
        console.log(response)
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.isOpenBingErpModal = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        branchId: undefined,
        agentId: undefined,
        storeId: this.storeId,
        storeUserName: this.storeUserName,
        storeAlias: undefined,
        personId: undefined
      };
      this.resetForm("formRef");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/userInfo/export', {
        ...this.queryParams
      }, `userInfo_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
